// https://www.lintcode.com/problem/multiply-two-numbers/
/**
 * Definition for ListNode
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */

public class Solution {
    /**
     * @param l1: the first list
     * @param l2: the second list
     * @return: the product list of l1 and l2
     */
    public long multiplyLists(ListNode l1, ListNode l2) {
        // write your code here
        long ret = 0;
        long i = 1;
        l1 = reverse(l1);
        l2 = reverse(l2);
        while (l1 != null) {
            long j = 1;
            ListNode tmp = l2;
            while (tmp != null) {
                ret += i * j * l1.val * tmp.val;
                tmp = tmp.next;
                j *= 10;
            }
            i *= 10;
            l1 = l1.next;
        }
        return ret;
    }
    
    protected ListNode reverse(ListNode l) {
        ListNode head = null, tail = null;
        while (l != null) {
            if (head != null) {
                ListNode tmp = l.next;
                l.next = head;
                head = l;
                l = tmp;
            } else {
                head = l;
                tail = l;
                l = l.next;
                tail.next = null;
            }
        }
        return head;
    }
}